import csv


def write2csv(table_head, content):
    # 1. 创建文件对象
    f = open('user_info.csv', 'w', encoding='utf-8', newline='')
    # 2. 基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)
    # 3. 构建列表头
    csv_writer.writerow(table_head)

    for each in content:
        csv_writer.writerow(each)
    print('user_info.csv 写入成功')
    f.close()


def main():
    ROW = ['性别', '体重(kg)', '身高(cm)', '年龄', '基础代谢率(大卡)']
    content = []
    i = 0
    y_or_n = input('是否退出程序(y/n)？')
    while y_or_n != 'y':
        try:
            print('请输入以下信息，用空格分隔')
            input_str = input('性别 体重(kg) 身高(cm) 年龄：')
            str_list = input_str.split(' ')
            gender = str_list[0]
            weight = float(str_list[1])
            height = float(str_list[2])
            age = int(str_list[3])

            if gender == '男':
                bmr = (13.7 * weight) + (5.0 * height) - (6.8 * age) + 66
            elif gender == '女':
                bmr = (9.6 * weight) + (1.8 * height) - (4.7 * age) + 655
            else:
                bmr = -1

            if bmr != -1:
                i = i + 1
                content.append([gender, weight, height, age, bmr])
                print('您的基础代谢率(大卡)是：', bmr)
                print('您一共运行了', i, '次')
            else:
                print('暂不支持该性别')
        except ValueError:
            print('请输入正确的信息！')
        except IndexError:
            print('输入的信息过少！')
        except:
            print('程序异常！')
        print()
        y_or_n = input('是否退出程序(y/n)？')
    write2csv(ROW, content)


if __name__ == '__main__':
    main()
